package com.riku.security.service.impl;

import com.riku.security.common.SnowFlake;
import com.riku.security.mapper.SeRoleUserMapper;
import com.riku.security.model.SeRoleUser;
import com.riku.security.model.SeUser;
import com.riku.security.service.SeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 1 on 2021/5/18.
 */
@Service
public class SeUserServiceImpl implements SeUserService{
    @Autowired
    private SeRoleUserMapper seRoleUserMapper;

    @Autowired
    private SnowFlake snowFlake;

    @Override
    public List<SeRoleUser> selectByName(String serviceCode, String userName) {
        SeRoleUser query = new SeRoleUser();
        query.setServiceCode(serviceCode);
        query.setUserName(userName);

        List<SeRoleUser> list = seRoleUserMapper.selectByName(query);
        return list;
    }

    @Override
    public List<SeRoleUser> selectUserDetail(String serviceCode, String userId) {
        SeRoleUser query = new SeRoleUser();
        query.setServiceCode(serviceCode);
        query.setUserId(userId);

        return seRoleUserMapper.selectDetailByUserId(query);
    }

    @Override
    public void deleteUser(String serviceCode, String userId) {
        SeRoleUser param = new SeRoleUser();
        param.setServiceCode(serviceCode);
        param.setUserId(userId);
        seRoleUserMapper.deleteByUserId(param);
    }

    @Override
    @Transactional
    public void insertUser(String serviceCode, String userId, String userName, List<Long> roleIds) {
        SeRoleUser entity = new SeRoleUser();
        entity.setId(snowFlake.nextId());
        entity.setServiceCode(serviceCode);
        entity.setUserId(userId);
        entity.setUserName(userName);
        for (Long roleId : roleIds) {
            entity.setRoleId(roleId);
            seRoleUserMapper.insert(entity);
        }

    }

    @Override
    @Transactional
    public void updateUser(String serviceCode, String userId, String userName, List<Long> roleIds) {
        SeRoleUser entity = new SeRoleUser();
        entity.setId(snowFlake.nextId());
        entity.setServiceCode(serviceCode);
        entity.setUserId(userId);
        entity.setUserName(userName);

        seRoleUserMapper.deleteByUserId(entity);
        for (Long roleId : roleIds) {
            entity.setRoleId(roleId);
            seRoleUserMapper.insert(entity);
        }
    }

    @Override
    public void deleteRoleUser(Long id) {
        seRoleUserMapper.deleteByPrimaryKey(id);
    }
}
